//
//  GoodsDetail.m
//  Wujin
//
//  Created by 东 on 16/12/7.
//  Copyright © 2016年 dong. All rights reserved.
//

#import "GoodsDetail.h"

#import "GoodNameCell.h"
#import "OrderDetail.h"

#import <WebKit/WebKit.h>

@interface GoodsDetail ()<UITableViewDelegate, UITableViewDataSource, WKNavigationDelegate>
{
    __weak IBOutlet UITableView *_tableView;
    __weak IBOutlet UIImageView *_headImage;
    __weak IBOutlet UIView      *_shopView;
    CGFloat tableFooterHeight;
    __weak IBOutlet NSLayoutConstraint *_shopViewBottom;
    __weak IBOutlet UILabel *_priceLab;
    GoodsModel      *_model;
    OrderGoodsModel *_orderGoodsModel;
    GoodNameCell    *_nameCell;
    CGFloat _cellHeight;
    __weak IBOutlet UIButton *_addShoppingCarBtn;
    __weak IBOutlet UIButton *_addOrderBtn;
}

@property (strong ,nonatomic)WKWebView *webView;

@end

@implementation GoodsDetail

- (void)viewDidLoad
{
    [super viewDidLoad];
    //给个返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backClick)];
    _tableView.bounces = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _addShoppingCarBtn.layer.cornerRadius = 5;
    _addShoppingCarBtn.layer.masksToBounds = YES;
    _addOrderBtn.layer.cornerRadius = 5;
    _addOrderBtn.layer.masksToBounds = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

#pragma mark - setter
- (void)setGoodsID:(NSString *)goodsID
{
    _goodsID = goodsID;
    
    [self getData];
}

#pragma mark - 加入购物车
- (IBAction)addShoppingCar:(id)sender
{
    int count = [_orderGoodsModel.Count intValue];
    if (count > 0)
    {
        NSMutableDictionary *mDict = _orderGoodsModel.mj_keyValues;
        NSString *datetime = [dbase.dateFormatter stringFromDate:[NSDate date]];
        [mDict setValue:datetime forKey:@"Datetime"];
        
        BOOL addCarSuccess = [dbase insertToTable:DB_GOODS values:mDict];
        if (addCarSuccess)
        {
            [MRHud show];
            [MRHud dismissWithSuccess:@"加入成功"];
        }
    }
    else
    {
        [MRAlert alertWithMessage:@"请输入有效数量"];
    }
}


#pragma mark - 立即下单
- (IBAction)makeOrder:(id)sender
{
    int count = [_orderGoodsModel.Count intValue];
    if (count > 0)
    {
        OrderDetail *detail = [UIViewController storyboardWithName:@"Car" storyboardID:@"orderdetail"];
        detail.dataArray = @[_orderGoodsModel];
        [self pushViewController:detail];
    }
    else
    {
        [MRHud show];
        [MRHud dismissWithFailure:@"请选择有效的商品"];
    }

}


#pragma mark - 获取数据
- (void)getData
{
    NSDictionary *dict = @{
                           @"goods_id" : _goodsID
                           };
    NSString *url = F(@"%@Index/getGoodsDetails", BASEURL);

    [FSServer requestWithTarget:url param:dict result:^(id responseObject, NSError *error) {
        if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            NSDictionary *dict = responseObject;
            if ([dict[@"flag"] intValue] == 1)
            {
                GoodsModel *model = [GoodsModel yy_modelWithDictionary:dict[@"data"]];
                [_headImage sd_setImageWithURL:[NSURL URLWithString:model.gds_img]];
                
                _model = model;
                self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 100)];
                NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:model.gds_details_url]];
                self.webView.navigationDelegate = self;
                [self.webView loadRequest:request];
                [_tableView reloadData];
            }
        }
    }];
}

#pragma mark - tableView datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0)
    {
        GoodNameCell *cell = [tableView dequeueReusableCellWithIdentifier:@"goodsname"];
        cell.model = _model;
        _priceLab.text = _model.price;
        cell.priceChangeBlock = ^(OrderGoodsModel *orderGoodsModel){
            _priceLab.text = F(@"%@", orderGoodsModel.TotalPrice);
            _orderGoodsModel = orderGoodsModel;
        };
        
        _nameCell = cell;
        return cell;
    }
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        return _nameCell.maxHeight;
    }
    return 44;
}

//当tableview 滚动的时候 结束编辑事件  （退出键盘）
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

#pragma mark - 处理键盘事件
- (void)keyboardDidChangeFrame:(NSNotification *)noti
{
    self.view.window.backgroundColor = _tableView.backgroundColor;
    
    CGRect frame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat keyY = frame.origin.y;
    
    CGFloat screenH = [[UIScreen mainScreen] bounds].size.height;
    
    CGFloat keyDuration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    _shopViewBottom.constant = -(keyY - screenH);
    [UIView animateWithDuration:keyDuration animations:^{
        [self.view layoutIfNeeded];
    }];
}


#pragma mark - webview delegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    [self.webView evaluateJavaScript:@"document.body.clientHeight" completionHandler:^(id _Nullable object, NSError * _Nullable error) {
        tableFooterHeight = [object doubleValue];
        self.webView.frame = CGRectMake(10, 40, ScreenWidth, tableFooterHeight + 10);
        _tableView.tableFooterView = [self tableFooterView];
    }];
}

#pragma mark - 创建底部视图
- (UIView *)tableFooterView
{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, tableFooterHeight + 10)];
    footerView.backgroundColor = [UIColor whiteColor];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(8, 10, 100, 22)];
    label.text = @"图文详情";
    label.font = [UIFont systemFontOfSize:15];
    label.textColor = skin.skinColor;
    [footerView addSubview:label];
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.3)];
    line1.backgroundColor = [UIColor darkGrayColor];
    [footerView addSubview:line1];
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, 39, ScreenWidth, 0.3)];
    line2.backgroundColor = [UIColor darkGrayColor];
    [footerView addSubview:line2];
    
    UIScrollView *tempView=(UIScrollView *)[self.webView.subviews objectAtIndex:0];
    tempView.scrollEnabled=YES;
    [footerView addSubview:self.webView];
    return footerView;
}

- (void)backClick{
    //点击返回
    [self.navigationController popViewControllerAnimated:YES];
}

@end
